// tea_score.js
let layerIndex;
let $;
var toast;
var table;

/**
 * 获取当前登录教师的ID
 * @returns {Promise<number>}
 */
async function getCurrentTeacherId() {
    const userId = JSON.parse(sessionStorage.getItem('userInfo'))?.userId;
    if (!userId) {
        console.error("用户未登录或sessionStorage无userInfo");
        window.location.href = "/login";
        throw new Error("用户未登录");
    }

    try {
        const res = await $.ajax({
            url: "/api/admin/teacher/getByUserId",
            method: "GET",
            data: { userId: userId },
        });

        // 根据你的返回数据结构调整
        if (res.code === 0) {
            // 直接返回教师ID，因为API返回的是Teacher对象
            console.log("获取到的教师信息:", res.data);
            return res.data; // 修改这里
        } else {
            console.error("获取教师ID失败:", res.msg);
            return userId;
        }
    } catch (error) {
        console.error("AJAX请求失败:", error);
        return userId;
    }
}

/**
 * 获取当前登录学生的ID
 * @returns {number}
 */
async function getCurrentStudentId() {
    const userId = JSON.parse(sessionStorage.getItem('userInfo'))?.id;
    if (!userId) {
        console.error("用户未登录或sessionStorage无userInfo");
        window.location.href = "/login";
        throw new Error("用户未登录");
    }

    try {
        const res = await $.ajax({
            url: "/api/admin/student/getByUserId",
            method: "GET",
            data: { userId: userId },
        });

        // 根据你的返回数据结构调整
        if (res.code === 0) {
            // 直接返回教师ID，因为API返回的是Teacher对象
            console.log("获取到的信息:", res.data);
            return res.data; // 修改这里
        } else {
            console.error("获取教师ID失败:", res.msg);
            return userId;
        }
    } catch (error) {
        console.error("AJAX请求失败:", error);
        return userId;
    }
}


/**
 * 初始化成绩表格
 */
function initScoreTable(teacherId) {

    console.log("老师id：", teacherId)
    if (!teacherId) {
        layer.msg('请先登录', {icon: 2});
        return;
    }
    table.render({
        elem: "#tbStudent",
        url: "/api/admin/teacher/getbypage",
        method: "POST",
        contentType: "application/json",
        request: {
            pageName: 'page',
            limitName: 'limit'
        },
        where: { // 修改这里，直接发送JSON字符串
            data: {
                teacher: {
                    teacherId: teacherId
                }
            }
        },
        page: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'courseId', fixed: 'left', width: 80, title: 'ID', sort: true},
            {field: 'courseName', title: '课程名称'},
            {field: 'courseCode', title: '课程代码', width: 80},
            {
                field: 'stuName',
                title: '学生姓名',
                templet: function (d) {
                    return d.student ? d.student.stuName : 'N/A';
                }
            },
            {
                field: 'stuNumber',
                title: '学号',
                templet: function (d) {
                    return d.student ? d.student.stuNumber : 'N/A';
                }
            },
            {
                field: 'className',
                title: '班级',
                templet: function (d) {
                    return d.student ? d.student.className : 'N/A';
                }
            },
            // {
            //     field: 'teacher.name', title: '授课教师', width: 120, templet: function (d) {
            //         return d.teacher ? d.teacher.name : '';
            //     }
            // },
            {field: 'score', title: '成绩', width: 100, sort: true},
            {fixed: 'right', title: "操作", width: 134, minWidth: 125, templet: "#editTemplate"}
        ]],
        done: function (rs) {
            console.log(rs)
        }
    });
}


/**
 * 显示编辑成绩对话框
 */
function showEditScoreDlg(data) {
    console.log("当前行数据：", data);

    // 确保数据结构正确
    const studentName = data.student?.stuName || '未知学生';
    const courseName = data.courseName || '未知课程';

    // 保存当前编辑的数据ID
    window.currentEditData = data;

    // 构建对话框内容，保持原始结构但动态填充数据
    const dialogContent = `
        <div style="padding: 20px;">
            <form class="layui-form" id="scoreForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">ID</label>
                    <div class="layui-input-block">
                        <input type="text" name="id" value="${data.courseId}" disabled class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">课程名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="courseName" value="${data.courseName || ''}" disabled class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">课程代码</label>
                    <div class="layui-input-block">
                        <input type="text" name="courseCode" value="${data.courseCode || ''}" disabled class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">系名</label>
                    <div class="layui-input-block">
                        <input type="text" name="department" value="${data.student.department || ''}" disabled class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">学生姓名</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" value="${data.student.stuName || ''}" disabled class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">成绩</label>
                    <div class="layui-input-block">
                        <input type="text" name="score" value="${data.score || ''}" 
                               lay-verify="required|score" autocomplete="off" 
                               class="layui-input">
                    </div>
                </div>
            </form>
        </div>
    `;

    layerIndex = layer.open({
        type: 1,
        title: '编辑成绩 - ' + studentName + ' (' + courseName + ')',
        content: dialogContent, // 直接使用动态生成的内容
        area: ['500px', '400px'],
        btn: ['保存', '取消'],
        yes: function(index, layero) {
            // submitScoreForm();
            // layer.close(index);
            // 直接从DOM获取值，不依赖layui表单
            const scoreInput = layero.find('input[name="score"]');
            const scoreValue = scoreInput.val().trim();

            // 使用保存的原始数据ID
            const requestData = {
                id: data.courseId,
                score: scoreValue
            };

            console.log("发送成绩更新请求:", requestData);

            $.ajax({
                url: "/api/admin/teacher/updateScore",
                method: "PUT",
                contentType: "application/json",
                data: JSON.stringify(requestData),
                success: function(res) {
                    if (res.code === 0) {
                        layer.msg('成绩更新成功', {icon: 1});
                        table.reload('tbStudent');
                        layer.close(index);
                    } else {
                        layer.msg(res.msg || '成绩更新失败', {icon: 2});
                        console.error("成绩更新失败:", res);
                    }
                },
                error: function(xhr, status, error) {
                    layer.msg('服务器错误，请稍后重试', {icon: 2});
                    console.error("成绩更新请求失败:", status, error);
                    console.error("响应内容:", xhr.responseText);
                }
            });
        },
        success: function(layero, index) {
            // 重新渲染表单元素
            layui.form.render();

            // 设置焦点到成绩输入框
            setTimeout(() => {
                layero.find('input[name="score"]').focus();
            }, 100);
        }
    });
}


// /**
//  * 搜索功能
//  */
// function search() {
//     const formData = form.val('queryForm');
//     const queryParams = {
//         teacherId: JSON.parse(sessionStorage.getItem('userInfo'))?.id,
//         courseName: formData.courseName,
//         courseCode: formData.courseCode,
//         name: formData.name,
//         sno: formData.sno,
//         department: formData.department
//     };
//
//     table.reload("tbStudent", {
//         where: queryParams,
//         page: {curr: 1}
//     });
// }

/**
 * 获取搜索条件
 */
function getSearchCondition() {
    const formData = {};
    $("#queryForm input[name], #queryForm select[name]").each(function() {
        const name = $(this).attr("name");
        const value = $(this).val().trim();
        if (value) {
            formData[name] = value;
        }
    });
    return formData;
}

/**
 * 搜索功能
 */
function search() {
    const searchCondition = getSearchCondition();
    (async () => {
        try {
            const teacherId = await getCurrentTeacherId();

            // 构建符合后端接口要求的查询参数
            const queryObj = {
                page: 1,
                limit: 10,
                data: {
                    teacher: { id: teacherId },
                    course: {
                        courseName: searchCondition.courseName,
                        courseCode: searchCondition.courseCode
                    },
                    student: {
                        name: searchCondition.name
                    }
                }
            };

            console.log("发送的查询参数:", queryObj);

            table.reload("tbStudent", {
                where: queryObj,
                page: { curr: 1 }
            });
        } catch (error) {
            console.error("查询失败:", error);
            layer.msg('查询失败: ' + error.message, { icon: 2 });
        }
    })();
}

layui.use(['form', 'table', 'layer'], function () {
    $ = layui.$;
    toast = layui.layer;
    table = layui.table;
    form = layui.form;

    // 确保表单渲染
    form.render();
    // 提交表单
    form.on('submit(stud-dlg)', function(data) {
        submitScoreForm();
        return false;
    });

    // 初始化表格
    (async () => {
        try {
            const teacherId = await getCurrentTeacherId();
            console.log("当前教师ID:", teacherId);
            initScoreTable(teacherId);
        } catch (error) {
            console.error("初始化失败:", error);
            layer.msg('初始化失败: ' + error.message, {icon: 2});
        }
    })();

    // 监听行工具事件
    table.on('tool(tbStudent)', function (obj) {
        const data = obj.data;
        if (obj.event === 'edit') {
            showEditScoreDlg(data);
        }
    });
});
